﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using System.Web.Http.ValueProviders;

using ProjectBase.Core;

using $prjsn$.RestApi;

namespace $safeprojectname$.RestApi
{
    public class FilterModelBinder : IModelBinder
    {
        public virtual bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var valueProvider = bindingContext.ValueProvider;

            var action = actionContext.ActionDescriptor.ActionName;
            if (action.IsEqual("Query"))
            {
                var message = new ServiceMessage();

                var query = actionContext.ControllerContext.Request.RequestUri.PathAndQuery;
                var odataProvider = new ODataParser().Parse(query, ref message);

                if (message.Messages.IsEmpty() && odataProvider.Is())
                {
                    valueProvider = odataProvider;
                }
                else
                {
                    actionContext.ControllerContext.Request.Properties["ODataServiceMessage"] = message;
                }
            }

            var binder = actionContext.ControllerContext.Controller as IFilterApiBinder<IFilter<int>, int>;
            if (binder.Is())
            {
                bindingContext.Model = binder.BindFilter(valueProvider);
                return true;
            }
            return false;
        }
    }
}